package handler

import (
	"context"
	"github.com/golang/protobuf/ptypes/empty"
	"go.uber.org/zap"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"sale_system/userop_srv/global"
	"sale_system/userop_srv/model"
	"sale_system/userop_srv/proto"
)

type MessageServer struct {
	proto.UnimplementedMessageServer // 一定需要实现这个接口
}

func (s *MessageServer) mustEmbedUnimplementedGoodsServer() {
	//TODO implement me
	panic("implement me")
}

func (s *MessageServer) MessageList(ctx context.Context, request *proto.MessageRequest) (*proto.MessageListResponse, error) {
	var rsp proto.MessageListResponse
	var messages []model.LeavingMessages
	var messageList []*proto.MessageResponse

	result := global.DB.Where(&model.LeavingMessages{User: request.UserId}).Find(&messages)
	if result.RowsAffected == 0 {
		zap.S().Infof("对应用户并没有留言")
		return nil, status.Error(codes.NotFound, "查找不到留言信息")
	}
	rsp.Total = int32(result.RowsAffected)

	for _, message := range messages {
		messageList = append(messageList, &proto.MessageResponse{
			Id:          message.ID,
			UserId:      message.User,
			MessageType: message.MessageType,
			Subject:     message.Subject,
			Message:     message.Message,
			File:        message.File,
		})
	}

	rsp.Data = messageList
	return &rsp, nil
}
func (s *MessageServer) CreateMessage(ctx context.Context, request *proto.MessageRequest) (*proto.MessageResponse, error) {

	message := model.LeavingMessages{
		User:        request.UserId,
		Message:     request.Message,
		MessageType: request.MessageType,
		Subject:     request.Subject,
		File:        request.File,
	}
	global.DB.Save(&message)

	return &proto.MessageResponse{Id: message.ID}, nil
}

// 实际上并没有提供这个接口
func (s *MessageServer) DeleteMessage(ctx context.Context, request *proto.MessageRequest) (*empty.Empty, error) {

	result := global.DB.Where("id = ? and user = ?", request.Id, request.UserId).Delete(&model.LeavingMessages{})
	if result.RowsAffected == 0 {
		zap.S().Info("删除失败")
		return &empty.Empty{}, status.Error(codes.Internal, "删除失败")
	}
	return &empty.Empty{}, nil
}
